package cn.com.startai.smartadh5.main.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.db.manager.PlayInfoHelper;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.extension.utils.NmcUtils;
import cn.com.startai.smartadh5.main.view.BannerLayout;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayStateChangeBean;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayModeChangedEvent;


/**
 * @author 尹晓童
 *         邮箱：yinxtno1@yeah.net
 *         时间：2018/2/5
 *         作用：
 */

public class ImageFragment extends BaseFragment {

    /**
     * 加载图片
     */
    private static final int HANDLER_WHAT_LOAD_IMAGE = 0x01;
    private BannerLayout banner;
    private ArrayList<PlayInfo> mPlayList = new ArrayList<>();

    public boolean isInit = false;
    private HandlerThread mHandlerThread;
    private Handler mHandler;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmnet_image, container, false);
    }

    @Override
    public void initData() {
        initHandler();
        EventBus.getDefault().register(this);
    }

    private void initHandler() {
        mHandlerThread = new HandlerThread("[ImageFragment.HandlerThread]", Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HANDLER_WHAT_LOAD_IMAGE:
                        //查询播放列表
                        List<PlayInfo> playList = PlayInfoHelper.getInstance()
                                .queryListByType(PlayInfo.TYPE_IMAGE);

                        NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_IMAGE, playList);

                        if (playList.isEmpty()) {
                            NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
                            return;
                        }

                        //得到当前播放的id
                        long playId = SPManager.getInstance().getCurrentAudioPlayId();

                        mContext.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int position = 0;
                                if (playId != -1) {
                                    for (int i = 0; i < playList.size(); i++) {
                                        if (playList.get(i).getId().equals(playId)) {
                                            position = i;
                                            break;
                                        }
                                    }
                                }
                                setUp(playList);
                                banner.getViewPager().setCurrentItem(position);
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void initView() {
        banner = (BannerLayout) mFragmentRootView.findViewById(R.id.bl_banner);
    }

    @Override
    public void addViewListener() {
        banner.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                //回复云端
                int code = SPUtils.getInstance().getInt("getindex");
                if (code==3){
                    NmcUtils.sendToNmcPlayerStatusChanged(mPlayList.get(position % mPlayList.size()).getFileId(),
                            PlayStateChangeBean.STATUS_PLAY, 0);
                    Log.i("ImageFragment","onPageSelected");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        banner.setOnPlayStateChangedListener(new BannerLayout.OnPlayStateChangedListener() {
            @Override
            public void onPlay(int position) {
                if (mPlayList.size() == 0) {
                    return;
                }
                int code = SPUtils.getInstance().getInt("getindex");
                Log.i("ImageFragment ","code="+code);
                if (code==3){
                    NmcUtils.sendToNmcPlayerStatusChanged(mPlayList.get(position % mPlayList.size()).getFileId(),
                            PlayStateChangeBean.STATUS_PLAY, 0);
                    Log.i("ImageFragment ","State Change code="+code);
                }
            }

            @Override
            public void onPause(int position) {
                if (mPlayList.size() == 0) {
                    return;
                }
                banner.setPlaying(false);
                NmcUtils.sendToNmcPlayerStatusChanged(mPlayList.get(position % mPlayList.size()).getFileId(),
                        PlayStateChangeBean.STATUS_PAUSE, 0);
            }
        });
    }

    public void setUp(List<PlayInfo> playList) {
        if (playList.isEmpty()) {
            return;
        }
        mPlayList.clear();
        mPlayList.addAll(playList);
        mPlayList.trimToSize();
        banner.setDatas(mPlayList);
    }

    public void appendPlayList(List<PlayInfo> playList) {
        if (playList.isEmpty()) {
            return;
        }
        mPlayList.addAll(playList);
        mPlayList.trimToSize();
        banner.appendData(playList);
    }

    /**
     * 删除指定播放记录
     *
     * @param removeFileId 当前删除的播放记录，>-1 为删除单条，=-1为清空操作
     */
    public void removePlayInfo(int removeFileId) {
        if (removeFileId > -1) {
            //删除单条

        } else {
            //删除所有
            mPlayList.clear();
            banner.setDatas(mPlayList);
        }
    }

    /**
     * 改变播放状态
     *
     * @param state 要改变的状态
     */
    public void changePlayState(PlayStateChangeBean state) {
        if (state.getStatus() == PlayStateChangeBean.STATUS_PLAY) {
            banner.setPlaying(true);
            Log.i("ImageFragment","changePlayState set true");
        } else {
            banner.setPlaying(false);
        }
    }
    public void setLoopMode(int mode) {
        if (banner == null) {
            return;
        }
        banner.setLoopMode(mode);
    }

    @Override
    public void onLeftPress() {
        super.onLeftPress();
        banner.pre();
    }

    @Override
    public void onRightPress() {
        super.onRightPress();
        banner.next();
    }

    @Override
    public void onInVisible() {
        super.onInVisible();
        if (banner == null) {
            return;
        }
        Log.i("ImageFragment ","onInVisible");
        SPUtils.getInstance().put("getindex",2);
        banner.setPlaying(false);
    }

    @SuppressWarnings("unused")
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onPlayModeChange(PlayModeChangedEvent event) {
        if(event.getMode() == PlayInfo.TYPE_IMAGE) {
            if (!isInit) {
                mHandler.sendEmptyMessage(HANDLER_WHAT_LOAD_IMAGE);
                isInit = true;
                return;
            }
            NmcUtils.sendToNmcPlayListChanged(PlayInfo.TYPE_IMAGE, mPlayList);
            if (mPlayList.isEmpty()) {
                NmcUtils.sendToNmcPlayerStatusChanged(-1, 0, 0);
            }
        }
    }

    @Override
    public void onVisible() {
        super.onVisible();
        SPManager.getInstance().saveCurrentPlayerMode(PlayInfo.TYPE_IMAGE);
        if(!mPlayList.isEmpty()) {
            banner.setPlaying(true);
        }
        Log.i("ImageFragment ","onVisible");
    }

//    @Override
//    public void onPause() {
//        super.onPause();
//        banner.setPlaying(false);
//    }

//    @Override
//    public void onStart() {
//        super.onStart();
//        if(SPManager.getInstance().getCurrentPlayerMode() != PlayInfo.TYPE_IMAGE) {
//            return;
//        }
//        int code = SPUtils.getInstance().getInt("getImg");
//        if (code==3){
//            banner.setPlaying(true);
//            Log.i("iM")
//        }
//    }

    @Override
    public void onStop() {
        super.onStop();
        banner.setPlaying(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.v("ImageFragment","onDestroyView");
        mHandlerThread.quit();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        mHandlerThread = null;
        EventBus.getDefault().unregister(this);
    }
}
